package com.itkjb.leisurely.resource.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itkjb.leisurely.core.base.service.impl.BaseServiceImpl;
import com.itkjb.leisurely.resource.sys.mapper.SysUserMapper;
import com.itkjb.leisurely.resource.sys.model.SysUserInfoModel;
import com.itkjb.leisurely.resource.sys.model.SysUserModel;
import com.itkjb.leisurely.resource.sys.service.ISysDepartmentService;
import com.itkjb.leisurely.resource.sys.service.ISysUserInfoService;
import com.itkjb.leisurely.resource.sys.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author itkjb.com
 * @since 2020-07-17
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUserModel> implements ISysUserService {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    ISysUserInfoService sysUserInfoService;

    @Autowired
    ISysDepartmentService sysDepartmentService;


    @Override
    public SysUserModel getUserInfoDetailById(Serializable userId) {
        SysUserModel sysUserModel =  getById(userId);

        return sysUserModel;
    }

    @Override
    public SysUserModel getById(Serializable id) {
        SysUserModel sysUserModel = super.getById(id);
        if(sysUserModel !=null ){
            SysUserInfoModel userInfoModel = this.sysUserInfoService.getById(id);
            if(userInfoModel !=null){
                sysUserModel.setUserInfo(userInfoModel);
            }
        }
        return sysUserModel;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(SysUserModel entity) {
        encoderPassword(entity);
        super.save(entity);
        SysUserInfoModel sysUserInfoModel = entity.getUserInfo();
        if (sysUserInfoModel == null) {
            sysUserInfoModel = new SysUserInfoModel();
        }
        sysUserInfoModel.setId(entity.getId());
        return sysUserInfoService.save(sysUserInfoModel);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(SysUserModel entity) {
        encoderPassword(entity);
        SysUserInfoModel sysUserInfoModel = entity.getUserInfo();
        if (sysUserInfoModel != null) {
            sysUserInfoModel.setId(entity.getId());
            SysUserInfoModel byId = sysUserInfoService.getById(sysUserInfoModel);
            if(byId !=null){
                sysUserInfoService.updateById(sysUserInfoModel);
            }else{
                sysUserInfoService.save(sysUserInfoModel);
            }
        }
        return super.updateById(entity);
    }

    /**
     * 加密密码
     *
     * @param entity
     */
    protected void encoderPassword(SysUserModel entity) {
        if (StringUtils.isNotBlank(entity.getPassword())) {
            entity.setPassword(passwordEncoder.encode(entity.getPassword()));
        }
    }

    /**
     * wrapper 组装器，构造条件查询
     *
     * @param wrapper
     * @param model   条件
     * @author itkjb.com
     * @date 2020-07-17
     **/
    @Override
    protected void assembleWrapper(QueryWrapper<SysUserModel> wrapper, SysUserModel model) {
        // （代码生成器生成）自动生成了，list查询的时候，条件组装，开发者自行删除不需要的条件
        // 用户名
        wrapper.lambda().eq(StringUtils.isNotBlank(model.getUsername()), SysUserModel::getUsername, model.getUsername());
        // 手机号
        wrapper.lambda().likeLeft(StringUtils.isNotBlank(model.getMobile()), SysUserModel::getMobile, model.getMobile());
        // 邮箱
        wrapper.lambda().eq(StringUtils.isNotBlank(model.getEmail()), SysUserModel::getEmail, model.getEmail());
        // 显示的名字
        wrapper.lambda().like(StringUtils.isNotBlank(model.getNickname()), SysUserModel::getNickname, model.getNickname());
        // 创建类型 1：后台添加 ，0: 用户注册
        wrapper.lambda().eq(model.getCreateType() != null, SysUserModel::getCreateType, model.getCreateType());
        // 默认组织id
        wrapper.lambda().eq(StringUtils.isNotBlank(model.getDefDepid()), SysUserModel::getDefDepid, model.getDefDepid());
        // 最后登陆时间
        wrapper.lambda().eq(model.getLastLogin() != null, SysUserModel::getLastLogin, model.getLastLogin());
        // 最后一次登陆ip
        wrapper.lambda().eq(StringUtils.isNotBlank(model.getLastIp()), SysUserModel::getLastIp, model.getLastIp());
        // 状态 0 创建，注册；2：待完善信息 ；4：待补充调整信息  8：正常 16：账户冻结
        wrapper.lambda().eq(model.getStatus() != null, SysUserModel::getStatus, model.getStatus());
    }

    /**
     * wrapper 组装器，组装list查询时，查询的列
     *
     * @param wrapper
     * @param model
     * @return void
     * @author itkjb.com
     * @date 2020-07-17
     * @since 2020-07-17
     **/
    @Override
    protected void buildListSelectColumns(QueryWrapper<SysUserModel> wrapper, SysUserModel model) {
        buildCommonSelectColumns(wrapper, model);
    }

    /**
     * 组装列表查询的列（字段）
     *
     * @param wrapper
     * @param model
     * @date 2020-07-17
     */
    protected void buildCommonSelectColumns(QueryWrapper<SysUserModel> wrapper, SysUserModel model) {
        // 代码生成器生成，为了简化开发时，查询list时，查询指定字段，没必要查询所有参数
        wrapper.lambda().select(
                // id
                SysUserModel::getId,
                // 用户名
                SysUserModel::getUsername,
                // 手机号
                SysUserModel::getMobile,
                // 邮箱
                SysUserModel::getEmail,
                // 显示的名字
                SysUserModel::getNickname,
                // 创建类型 1：后台添加 ，0: 用户注册
                SysUserModel::getCreateType,
                // 默认组织id
                SysUserModel::getDefDepid,
                // 最后登陆时间
                SysUserModel::getLastLogin,
                // 最后一次登陆ip
                SysUserModel::getLastIp,
                // 最后一次登录ip地址描述
                SysUserModel::getLastIpDes,
                // 状态 0 创建，注册；2：待完善信息 ；4：待补充调整信息  8：正常 16：账户冻结
                SysUserModel::getStatus,
                SysUserModel::getCreateTime
        );
    }


}
